package com.topisv.tms.web.stock.warehouseage;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.SkuOverInfo;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.SkuOverInfoService;
import com.topisv.tms.service.WarehouseAgeService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.task.warehouseage.JdbcUtil;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.web.base.BaseController;

@Controller
@RequestMapping({ "/warehouseAge" })
public class WarehouseAgeController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(WarehouseAgeController.class);
	@Autowired
	private SkuOverInfoService soiService;
	@Autowired
	private WarehouseAgeService waService;
	@Autowired
	private CustomersService customersService;
	
	@Autowired
	private AreaGroupService areaGroupService;
	
	/**
	 * 库龄查询页面
	 */
	@RequestMapping(value = "v2_warehouseAgePage")
	public String warehouseAgePage(Model model, ServletRequest request,
			ServletResponse response) {
		// 查出当前用户关联的商家列表
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		List<Customers> customerList = this.customersService.loadCustomerByAuthority(curUser);
//		model.addAttribute("customerList", customerList);
		model.addAttribute("userType", curUser.userType);
//		model.addAttribute("warehouseList", new ArrayList<AreaGroup>());
		fillSelectValue(model, null);
		return "/stock/warehouseage/warehouseAgePage";
	}

	/**
	 * 库龄查询页面
	 */
	@RequestMapping(value = "v2_warehouseAgeQuery")
	public String warehouseAgeQuery(Model model, ServletRequest request,
			ServletResponse response) {
		String customerCode = request.getParameter("customerCode");
		String warehouseCode = request.getParameter("warehouseCode");
		String sku = request.getParameter("sku");
		String endFlag = request.getParameter("endFlag");
		
		List<SkuOverInfo> soiList = soiService.findBy(warehouseCode, customerCode, sku,endFlag);
		
		//查出当前用户关联的商家列表
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
		//初始化仓库数据
		List<AreaGroup> warehouseList = new ArrayList<AreaGroup>();
		if(!StringUtils.isEmpty(customerCode)){
			warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
		}
				
				
		model.addAttribute("customerCode", customerCode);
		model.addAttribute("warehouseCode", warehouseCode);
		model.addAttribute("sku", sku);
		model.addAttribute("soiList", soiList);
		model.addAttribute("customerList",customerList);
		model.addAttribute("warehouseList", warehouseList);
		return "/stock/warehouseage/warehouseAgePage";
	}

	
	
	
	
	/**
	 * 库龄查询页面
	 */
	@RequestMapping(value = "v2_warehouseAgeQueryAjax", method=RequestMethod.POST)
	public void warehouseAgeQueryAjax(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) {
		JSONObject json=new JSONObject();
		Page<SkuOverInfo> page=null;
		try{
			//变量定义
			PrintWriter out=response.getWriter();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			//查询
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int pageSize = Integer.parseInt(paramMap.get("iDisplayLength")); 
			int pageNumber=(start/pageSize)+1;
			
			String customerCode = paramMap.get("customerCode");
			String warehouseCode = paramMap.get("warehouseCode");
			String sku = paramMap.get("sku");
			String endFlag = paramMap.get("endFlag");
			
			page = soiService.findBy(warehouseCode, customerCode, sku, endFlag,pageNumber,pageSize);
			List<SkuOverInfo> soiList = page.getContent();
			
			//封装查询结果
	        json.put("aaData", soiList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
			 out.print(json);
		}catch(Exception e){
			e.printStackTrace();
			json.put("result","false");
		}
//		return "/stock/warehouseage/warehouseAgePage";
	}

	/**
	 * 导出库龄
	 */
	@RequestMapping(value = "exportGoodsAgeExcell",method = RequestMethod.POST)
	public String exportGoodsAgeExcell(Model model, ServletRequest request,
			HttpServletResponse response) {
		try {
			logger.info("导出库龄信息。。。。");
			String customerCode = request.getParameter("customerCode");
			String warehouseCode = request.getParameter("warehouseCode");
			String sku = request.getParameter("sku");
			String endFlag = request.getParameter("endFlag");
			String fileName = "WarehouseAgeInfo";
			if(!StringUtils.isEmpty(customerCode)){
				fileName += "_" + customerCode;
			}
			if(!StringUtils.isEmpty(warehouseCode)){
				fileName += "_" + warehouseCode;
			}
			if(!StringUtils.isEmpty(sku)){
				fileName += "_" + sku;
			}
			List<SkuOverInfo> soiList = soiService.findBy(warehouseCode, customerCode, sku,endFlag);
			//List<SkuOverInfo> soiList = JdbcUtil.findByEndFlag(false);
			response.setHeader("Content-disposition","attachment; filename=" + new String((fileName).getBytes("gbk"),"utf-8") + ".xls");
			WritableWorkbook book  =  Workbook.createWorkbook(response.getOutputStream());
			int sheetIndex = 0;
			int rowIndex = 0;
			while(true){
				WritableSheet sheet  =  book.createSheet( "库龄信息( 第"+(sheetIndex+1)+"页)",sheetIndex);
				sheet.setColumnView(0, 20);//商家编码
				sheet.setColumnView(1, 20);//仓库编码
				sheet.setColumnView(2, 20);//SKU
				sheet.setColumnView(3, 20);//结算时间
				sheet.setColumnView(4, 20);//超时开始时间
				sheet.setColumnView(5, 20);//超时结束时间
				sheet.setColumnView(6, 15);//超时天数
				sheet.setColumnView(7, 15);//超龄数量
				sheet.setColumnView(8, 25);//当前状态
				
				int index = 0;
				Label label1 = new  Label(0,index ,"商家编码");
				sheet.addCell(label1);
				Label label2 = new  Label(1,index ,"仓库编码");
				sheet.addCell(label2);
				Label label3 = new  Label(2,index ,"SKU");
				sheet.addCell(label3);
				Label label4 = new  Label(3,index ,"入库时间");
				sheet.addCell(label4);
				Label label5 = new  Label(4,index ,"超时开始时间");
				sheet.addCell(label5);
				Label label6 = new  Label(5,index ,"超时结束时间");
				sheet.addCell(label6);
				Label label7 = new  Label(6,index ,"超时天数");
				sheet.addCell(label7);
				Label label8 = new  Label(7,index ,"超龄数量");
				sheet.addCell(label8);
				Label label9 = new  Label(8,index ,"当前状态");
				sheet.addCell(label9);
				
				while(true){
//				for(int i = rowIndex ; i < soiList.size();i++) {
					if(index == 60000||rowIndex>=soiList.size()){
						break;
					}
					SkuOverInfo soi = soiList.get(rowIndex);
					index++;
					rowIndex++;
					Label label11 = new  Label(0,index ,soi.getCustomerCode());
					sheet.addCell(label11);
					Label label12 = new  Label(1,index ,soi.getWarehouseCode());
					sheet.addCell(label12);
					Label label13 = new  Label(2,index ,soi.getSku());
					sheet.addCell(label13);
					Label label14 = new  Label(3,index ,soi.getOpeTimeStr());
					sheet.addCell(label14);
					Label label15 = new  Label(4,index ,soi.getStartTimeStr());
					sheet.addCell(label15);
					Label label16 = new  Label(5,index ,soi.getEndTimeStr());
					sheet.addCell(label16);
					Label label17 = new  Label(6,index ,soi.getOverDay()+"");
					sheet.addCell(label17);
					Label label18 = new  Label(7,index ,soi.getOverNum()+"");
					sheet.addCell(label18);
					Label label19 = new  Label(8,index ,(soi.getEndFlag()?"已结束超时状态":"未结束超时状态"));
					sheet.addCell(label19);
				}
				System.out.println(rowIndex);
				if(null != soiList&&rowIndex>=soiList.size()){
					break;
				}
				sheetIndex++;
				
			}
			logger.info("导出成功");
			book.write();
            book.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
		return "true";
	}

	@RequestMapping(value = "startWarehouseAge")
	public void startWarehouseAge(Model model,HttpServletResponse response,ServletRequest request) {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			waService.goodsAge();
			
			json.put("status", "1");
			json.put("content", "获取成功");
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
}